<?php

namespace App\Containers\AppSection\Moderation\Actions;

use App\Containers\AppSection\Log\Tasks\CreateLogTask;
use App\Containers\AppSection\Moderation\Models\Moderation;
use App\Containers\AppSection\Moderation\Tasks\CreateRemarkTask;
use App\Containers\AppSection\Moderation\Tasks\FindModerationByIdTask;
use App\Containers\AppSection\Moderation\Tasks\SendToModerationTask;
use App\Containers\AppSection\Project\Tasks\UpdateProjectTask;
use App\Ship\Parents\Actions\Action;
use App\Ship\Parents\Requests\Request;

class UpdateModerationAction extends Action
{

    public function run($id, Request $request): Moderation
    {
        $moderation = app(FindModerationByIdTask::class)->run($id);

        if ($request->getInputByKey('type') === 'projects_checking') {
            $moderation = app(SendToModerationTask::class)->run([
                'project_id' => $moderation->project->id,
                'stage' => 'moderator'
            ]);

            app(UpdateProjectTask::class)->run($moderation->project->id, [
                'moderation_status_key' => $request->getInputByKey('type'),
                'moderated_at' => null,
                'moderation_id' => $moderation->id
            ]);
        } else if ($request->getInputByKey('type') === 'projects_rejected') {
            app(UpdateProjectTask::class)->run($moderation->project->id, [
                'moderation_status_key' => $request->getInputByKey('type'),
                'moderated_at' => null
            ]);
        }

        if (!empty($request->getInputByKey('remarks'))) {
            foreach ($request->getInputByKey('remarks') as $remark) {
                app(CreateRemarkTask::class)->run([
                    'message' => $remark['message'],
                    'type_key' => null,
                    'moderation_id' => $moderation->id,
                    'profile_id' => $request->profile()->id
                ]);
            }
        }

        $log = '';
        switch ($request->getInputByKey('type')) {
            case 'projects_checking':
                $log = "Проект №{$moderation->project->id} отправлен на повторную проверку.";
                break;
            case 'projects_rejected':
                $log = "Проект №{$moderation->project->id} отклонен.";
                break;
        }


        app(CreateLogTask::class)->run($moderation->project->profile->id, $log, 'moderation', $moderation->id);
        app(CreateLogTask::class)->run($request->profile()->id, $log, 'moderation', $moderation->id);

        return $moderation;
    }
}
